package com.ly.mpayment.rest.up.maiyuan2;

import com.google.gson.JsonObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@Path("maiyuan2")
public class MaiYuan2Rest {
    static Logger logger = Logger.getLogger(MaiYuan2Rest.class);

    public static final String version = "h1.1";

    public static final String defaultStr = "v="+version+"&action=";

    public static final String codeSuccess = "0";

    public static final int range [] = {0,1};

    public static final int resultStatus [] = {4,3,5,7,2};

    @Autowired
    IUporderService upOrderService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;
//	返回错误定义
//	0	成功
//	001	参数错误
//	002	充值号码不合法
//	003	帐号密码错误
//	004	余额不足
//	005	不存在指定流量包
//	006	不支持该地区
//	007	卡号或者密码错误
//	008	该卡已使用过
//	009	该卡不支持(移动/电信/联通)号码
//	010	协议版本错误
//	999	其他错误


    /**
     * TaskID	任务编码	失败为0
     Code	代码	成功为0
     Message		消息	注意：启用商户订单号唯一性验证后，如果手机号码+商户订单号存在，Code会返回0，表示成功。Message提示为：商户订单号xxx已经存在
     但不会再新建订单，TaskID将会返回上一次相同商户订单号提交返回的TaskID。如果TaskID返回为-1，需要人工介入判断。

     * 单号码充值
     * @param phoneNum
     * @param upOrderUuid
     * @param packageNo
     * @return
     */
    @SuppressWarnings("static-access")
    public String charge(String phoneNum,String upOrderUuid,String packageNo,String account,String apikey
            ,String backurl,String commitUrl,UpOrder order){
        Map<String, Object> paras = MapUtil.getMap();
        paras.put("account", account);
        paras.put("mobile",phoneNum);
        paras.put("backurl",backurl);
        paras.put("package",packageNo);
        //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
        //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
        //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
        paras.put("mnp", order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "yd" :
                order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "lt" :
                        order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "dx" : "xx");
        paras.put("outtradeno", upOrderUuid);
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("account",account);
        object.put("mobile",phoneNum);
        object.put("package",packageNo);
        String url = defaultStr+"charge&account="+account+"&mobile="+phoneNum+"&backurl="+backurl+"&mnp="+paras.get("mnp")+
                "&outtradeno="+upOrderUuid+"&package="+packageNo+"&sign="+MD5.md5(StringSort.doSign(object)+"&key="+apikey);
        logger.info("maiyuan_charge:"+url+":"+StringSort.doSign(object)+"&key="+apikey);
        String result = HttpClient.httpGetUrl(commitUrl.concat("?")+url);
        logger.info("maiyuan_charge_result:"+result);
        if(!StringUtils.isBlank(result)){
            return result;
        }
        return null;
    }

    /**
     *     TaskID	任务
     Mobile	手机
     Status	状态	2.充值中(该状态时号码可能为空)
     3.提交失败
     4.充值成功
     5.充值失败
     7.未知(待处理)
     ReportTime	时间
     ReportCode	代码说明
     OutTradeNo	商户订单号	商户系统内部的订单号

     * @param upOrderUuid
     * @param sendTime
     * @return
     */
    public String queryReport(String upOrderUuid,String sendTime,String account,String apikey,String queryUrl,String phoneNum,String packageNo){
        Map<String, Object> paras = MapUtil.getMap();
        paras.put("account", account);
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("account",account);
        object.put("mobile",phoneNum);
        object.put("package",packageNo);
        String url = defaultStr+"getreport&account="+account+"&outtradeno="+upOrderUuid+"&mobile="+phoneNum+"&package="+packageNo
                +"&sign="+MD5.md5(StringSort.doSign(object)+"&key="+apikey);
        String result = HttpClient.httpGetUrl(queryUrl.concat("?")+url);
        if(!StringUtils.isBlank(result)){
            return result;
        }
        return null;
    }


    /**
     * 增加签名
     * {
     * 'taskid': '725703',
     * 'mobile': '13616688772',
     * 'status': 4,
     * 'reporttime': '2018-10-22 14:15:38',
     * 'reportcode':'0000:成功003420181022141532458759',
     * 'outtradeno': '2018102214152012803'
     * ‘serialnum’: ‘003420181022141532458759
     * }
     * @param data
     * @return
     */
    @SuppressWarnings("-access")
    @POST
    @Path("callBack")
    public synchronized String callBack(String data){
        logger.info("maiyuan_callBack:"+data);
        if(!StringUtils.isBlank(data)){
            try {
                JSONObject array = JSONObject.fromObject(data);
                    if(array.containsKey("taskid") && array.containsKey("outtradeno")){
                        UpOrder order = upOrderService.findById(array.getString("outtradeno").trim());
                        if(array.getString("status").equals("4") && order != null && order.getStatus() == Config.status[0]){
                            order.setRemark(StringUtils.isBlank(array.getString("serialnum")) ? "" : array.getString("serialnum"));
                            RechargeRest.successUpOrder.add(order);
                        }else if(array.getString("status").equals("5") && order != null && order.getStatus() == Config.status[0]){
                            order.setRemark(array.getString("status"));
                            RechargeRest.failtUpOrder.add(order);
                        }else{
                            logger.info("maiyuan_not_found_order:"+data);
                        }
                    }
                return "OK";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "falit";
    }

    public void commitOrder(UpOrder order, UpShopInfo shop) {
        try {
            UpOrder product = upOrderService.findOrderProduct(order.getUporderuuid());
            if (product != null) {
                String packages[] = product.getUpShopPro().getProductCode().split("\\|");
                String result = charge(order.getUpphonenum(), order.getUporderuuid(), product.getUpShopPro().getUpfacevalue(),
                        shop.getAppId(),shop.getUpkey(),shop.getOrderCallAddress(),shop.getOrderCommitAddress(),
                        order);
                logger.info("commitmaiyuan2_result:" + result);
                if (!StringUtils.isBlank(result)) {
                    try{
                        JSONObject json = JSONObject.fromObject(result);
                        if(json.getString("msg").equals("1")){
                            this.upOrderService.updateUpOrderMsg(order, json.getString("data"),json.getString("msg"));
                        }else if (result.contains("msg") && json.getString("msg").equals("0")) {
                            RechargeRest.failtUpOrder.add(order);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        upOrderService.updateUpOrderArtificial(order, "","提单失败:");
                    }
                } else {
                    this.upOrderService.updateUpOrderArtificial(order, "", Config.commitFailt);
                    logger.info("commitmaiyuan_error" + order.getUpphonenum());
                }
            }else{
                logger.info("commitmaiyuan error not found product" + order.getUporderuuid());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            this.upOrderService.updateUpOrderArtificial(order, "", Config.commitFailt);
            logger.info("commitmaiyuan_error+" + order.getUpphonenum());
        }
    }

    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        String result = queryReport(upOrder.getUporderuuid(), DateUtils.toShortDate(upOrder.getCreatetime()),shopInfo.getAppId(),
                shopInfo.getUpkey(),shopInfo.getOrderStatusAddress(),upOrder.getUpphonenum(),upOrder.getUpShopPro().getUpfacevalue());
        logger.info("maiyuan_queryReport:"+result);
        if(result != null){
            JSONObject json = JSONObject.fromObject(result);
            UpOrder order = upOrderService.findById(json.getString("outtradeno").trim());
            if(json.getInt("status") == 4 && order != null && order.getStatus() == Config.status[0]){
                order.setRemark(json.getString("status"));
                RechargeRest.successUpOrder.add(order);
            }else if( (json.getInt("status") == 5 || json.getInt("status") == 6) && order != null && order.getStatus() == Config.status[0]){
                order.setRemark(json.getString("status"));
                RechargeRest.failtUpOrder.add(order);
            }
        }else{
            logger.info("maiyuan order failt:"+upOrder.getUpphonenum());
        }
    }

}
